package actions;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import controller.ExamineDAORemote;
import controller.PatientDAORemote;
import entities.ExamineDetail;
import entities.PatientDetail;
import forms.OPatientActionForm;

public class OPatientAction extends Action {
	private PatientDAORemote paRemote;
	private ExamineDAORemote exRemote;

	public OPatientAction() {
		paRemote = lookupPaRemote();
		exRemote = lookupExaRemote();

	}

	public PatientDAORemote lookupPaRemote() {
		PatientDAORemote rmt = null;
		try {
			InitialContext ctx = new InitialContext();
			rmt = (PatientDAORemote) ctx
					.lookup("java:global/GoodHealth/GoodHealth-ejb/PatientDAO!controller.PatientDAORemote");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rmt;
	}

	public ExamineDAORemote lookupExaRemote() {
		ExamineDAORemote rmt = null;
		try {
			InitialContext ctx = new InitialContext();
			rmt = (ExamineDAORemote) ctx
					.lookup("java:global/GoodHealth/GoodHealth-ejb/ExamineDAO!controller.ExamineDAORemote");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rmt;
	}

	@SuppressWarnings("unchecked")
	public void getAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		List<PatientDetail> _pa = paRemote.getAllPatient();
		String result = "";

		JSONArray jsonArray = new JSONArray();
		for (PatientDetail pa : _pa) {
			JSONObject jObj = new JSONObject();
			String idUser;
			try {
				idUser = pa.getUser().getIdUser();

			} catch (Exception e) {
				idUser = "";
			}

			int dle = 0;
			List<ExamineDetail> _ex = pa.getExamineDetails();
			if (_ex.size() <= 1) {
				dle = 1;
			}
			jObj.put("idPatientDetail", pa.getIdPatientDetail());
			jObj.put("firstName", pa.getFirstName());
			jObj.put("lastName", pa.getLastName());
			jObj.put("emgContact", pa.getEmgContact());
			jObj.put("address", pa.getAddress());
			jObj.put("dle", dle);
			jObj.put("idUser", idUser);
			jsonArray.add(jObj);
		}

		result = jsonArray.toString();

		out.write(result);
	}

	public String create(ActionMapping mapping, OPatientActionForm actFrm) throws ParseException {
		String result = "";
		DateFormat dfm = new SimpleDateFormat("dd-MM-yyyy HH:mm");

		Date appointmentDay = dfm.parse(actFrm.getAppointmentDay() + " "
				+ actFrm.getAppointmentTime());
		result = paRemote.createPatient(actFrm.getFirstName(), actFrm.getLastName(),
				actFrm.getAddress(), actFrm.getEmgContact(), appointmentDay);

		return result;
	}

	public String delete(HttpServletRequest request) {
		String id = request.getParameter("id");
		String result = paRemote.deletePatient(id);
		return result;
	}

	public String edit(ActionMapping mapping, OPatientActionForm actFrm) {
		String result = paRemote.updatePatient(actFrm.getIdPatientDetail(), actFrm.getFirstName(),
				actFrm.getLastName(), actFrm.getAddress(), actFrm.getEmgContact());
		return result;
	}

	@SuppressWarnings("unchecked")
	public void getById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		PrintWriter out = response.getWriter();
		PatientDetail pa = paRemote.getPatientById(id);
		JSONObject jObj = new JSONObject();
		if (pa != null) {
			jObj.put("idPatientDetail", pa.getIdPatientDetail());
			jObj.put("firstName", pa.getFirstName());
			jObj.put("lastName", pa.getLastName());
			jObj.put("emgContact", pa.getEmgContact());
			jObj.put("address", pa.getAddress());
		}

		out.write(jObj.toString());
	}

	@SuppressWarnings("unchecked")
	public void getByName(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String firstName = request.getParameter("firstname");
		String lastName = request.getParameter("lastname");
		PrintWriter out = response.getWriter();
		List<PatientDetail> _pa = paRemote.getPatientByName(firstName, lastName);

		JSONArray _JsonArray = new JSONArray();
		if (!_pa.isEmpty()) {
			for (PatientDetail pa : _pa) {
				JSONObject jObj = new JSONObject();
				jObj.put("idPatientDetail", pa.getIdPatientDetail());
				jObj.put("firstName", pa.getFirstName());
				jObj.put("lastName", pa.getLastName());
				jObj.put("emgContact", pa.getEmgContact());
				jObj.put("address", pa.getAddress());
				_JsonArray.add(jObj);
			}
		}
		out.write(_JsonArray.toString());
	}

	@SuppressWarnings("unchecked")
	public void getExamine(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String idPatient = request.getParameter("id");
		PrintWriter out = response.getWriter();
		List<ExamineDetail> _ExamineDetails = paRemote.getPatientById(idPatient).getExamineDetails();
		JSONArray _JsonArray = new JSONArray();
		DateFormat dfm = new SimpleDateFormat("dd-MM-yyyy HH:mm");
		if (!_ExamineDetails.isEmpty()) {
			for (ExamineDetail examineDetail : _ExamineDetails) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("idExamine", examineDetail.getIdExamine());
				jsonObject.put("idPatient", examineDetail.getPatientDetail().getIdPatientDetail());
				jsonObject.put("doctor", examineDetail.getDoctor());
				jsonObject.put("appointmentDay", dfm.format(examineDetail.getAppointmentDay()));
				Date exa = examineDetail.getExamineDay();
				if (exa != null) {
					jsonObject.put("examineDay", dfm.format(exa));
				} else {
					jsonObject.put("examineDay", null);
				}
				jsonObject.put("disease", examineDetail.getDisease());

				_JsonArray.add(jsonObject);
			}
		}

		out.write(_JsonArray.toString());
	}

	public void deleteExamine(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String idExamine = request.getParameter("id");
		PrintWriter out = response.getWriter();
		String result = exRemote.deleteExamine(idExamine);
		out.write(result);
	}

	public void setMessage(HttpServletRequest request, String key) {
		ActionMessages messages = new ActionMessages();
		messages.add("message", new ActionMessage(key));
		saveMessages(request, messages);
	}

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String act = request.getParameter("act");
		OPatientActionForm actFrm = (OPatientActionForm) form;

		if (act.equals("getAll")) {
			getAll(request, response);
			return super.execute(mapping, form, request, response);
		} else if (act.equals("getbyid")) {
			getById(request, response);
			return super.execute(mapping, form, request, response);
		} else if (act.equals("getbyname")) {
			getByName(request, response);
			return super.execute(mapping, form, request, response);
		} else if (act.equals("getexamine")) {
			getExamine(request, response);
			return super.execute(mapping, form, request, response);
		} else if (act.equals("deleteexamine")) {
			deleteExamine(request, response);
			return super.execute(mapping, form, request, response);
		} else if (act.equals("create")) {
			if (create(mapping, actFrm).equals("success")) {
				setMessage(request, "success.common.patient.create");
			} else {
				setMessage(request, "fail.common.patient.create");
			}
		} else if (act.equals("edit")) {
			if (edit(mapping, actFrm).equals("success")) {
				setMessage(request, "success.common.patient.update");
			} else {
				setMessage(request, "fail.common.patient.update");
			}
		} else if (act.equals("delete")) {
			if (delete(request).equals("success")) {
				setMessage(request, "success.common.patient.delete");
			} else {
				setMessage(request, "fail.common.patient.delete");
			}
		}

		actFrm.reset(mapping, request);

		return mapping.findForward("default");

	}

}
